package com.future.mayi.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.future.baselib.utils.ApiCst;
import com.future.baselib.utils.HttpRequest;
import com.future.mayi.R;
import com.future.mayi.adapter.GoodsBatchAdapter;
import com.future.mayi.app.App;
import com.future.mayi.model.GoodsBatchModel;
import com.future.mayi.model.MultiPostfeeModel;
import com.future.mayi.model.SpecModel;
import com.future.mayi.response.GoodsSpecResponse;
import com.future.mayi.response.MultiPostfeeResponse;
import com.future.mayi.utils.HCUtils;
import com.future.mayi.utils.PriceUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class GoodsBatchActivity extends BaseTitleActivity {
    @BindView(R.id.iv_img)
    ImageView ivImg;
    @BindView(R.id.tv_goods_title)
    TextView tvGoodsTitle;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.tv_add)
    TextView tvAdd;
    @BindView(R.id.tv_enter)
    TextView tvEnter;
    private String goodsId, title, img;


    private GoodsBatchAdapter adapter;

    public static void startActivity(Context context, String goodsId, String title, String img) {
        Intent intent = new Intent(context, GoodsBatchActivity.class);
        intent.putExtra("goodsId", goodsId);
        intent.putExtra("title", title);
        intent.putExtra("img", img);
        context.startActivity(intent);
    }

    @Override
    protected void initTopBar() {
        initBack();
        getTitleText().setText("批量下单");
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_goods_batch);
    }

    @Override
    protected void initView() {
        adapter = new GoodsBatchAdapter(mContext);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);
    }

    @Override
    protected void initDates() {
        goodsId = getIntent().getStringExtra("goodsId");
        title = getIntent().getStringExtra("title");
        img = getIntent().getStringExtra("img");
        getGoodsData();
        tvGoodsTitle.setText(title);
        HCUtils.loadWebImg(mContext, ivImg, img);
    }

    @Override
    protected void initListener() {

    }


    private ArrayList<GoodsBatchModel> goodsBatchModels;

    @OnClick({R.id.tv_add, R.id.tv_enter})
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.tv_add:
                addItemView();
                break;
            case R.id.tv_enter:
                tvEnter.setEnabled(false);
                goodsBatchModels = (ArrayList<GoodsBatchModel>) adapter.getList();
                if (goodsBatchModels == null || goodsBatchModels.size() == 0) {
                    toast("最少添加一个订单");
                    tvEnter.setEnabled(true);
                    return;
                }
                for (int i = 0; i < goodsBatchModels.size(); i++) {
                    GoodsBatchModel model = goodsBatchModels.get(i);
                    if (model.getSelectList() == null || model.getSelectList().size() == 0) {
                        toast("订单" + (i + 1) + "商品信息不能为空");
                        recyclerView.smoothScrollToPosition(i);
                        tvEnter.setEnabled(true);
                        return;
                    }
                    if (TextUtils.isEmpty(model.getAddress())) {
                        toast("订单" + (i + 1) + "地址信息不能为空");
                        recyclerView.smoothScrollToPosition(i);
                        tvEnter.setEnabled(true);
                        return;
                    }
                }
                showLoadingDialog();
                getMultiPostfee(0);
                break;
        }
    }


    private void getMultiPostfee(final int position) {
        if (goodsBatchModels == null || goodsBatchModels.size() == 0) {
            dissmissLoadingDialog();
            return;
        }
        if (position >= goodsBatchModels.size()) {
            dissmissLoadingDialog();
            NewGoodsBatchOrderActivity.startActivity(this, goodsId, title, img, goodsBatchModels, 114);
            tvEnter.setEnabled(true);
            return;
        }
        GoodsBatchModel model = goodsBatchModels.get(position);
        new HttpRequest<MultiPostfeeResponse>()
                .with(mContext)
                .setApiCode(ApiCst.multiPostfeeGoods)
                .addParam("goods_id", model.getGoods_id())
                .addParam("order_info", model.getOrder_info())
                .addParam("token", App.getToken(mContext))
                .setListener(new HttpRequest.OnNetworkListener<MultiPostfeeResponse>() {

                    @Override
                    public void onSuccess(MultiPostfeeResponse response) {
                        MultiPostfeeModel multiPostfeeModel = response.model;
                        if (multiPostfeeModel == null) return;
                        goodsBatchModels.get(position).setPostage(multiPostfeeModel.getPost_fee());
                        getMultiPostfee(position + 1);
                    }

                    @Override
                    public void onFail(String message, MultiPostfeeResponse response) {
                        dissmissLoadingDialog();
                        HCUtils.loadFail(mContext, message);
                        recyclerView.smoothScrollToPosition(position);
                        tvEnter.setEnabled(true);
                    }
                }).start(new MultiPostfeeResponse());

    }


    private void addItemView() {
        GoodsBatchModel model = new GoodsBatchModel();
        List<SpecModel> list = new ArrayList<>(this.list.size());
        for (SpecModel specModel : this.list) {
            list.add(new SpecModel(specModel.getGoods_spec_id(), specModel.getGoods_no(), specModel.getGoods_price(), specModel.getGoods_spec(), specModel.getRebate_price(), specModel.getQuotas_price()));
        }
        model.setGoods_id(goodsId);
        model.setList(list);
        adapter.addMore(model);
        recyclerView.smoothScrollToPosition(adapter.getItemCount() - 1);
        recyclerView.postDelayed(new Runnable() {
            @Override
            public void run() {
                recyclerView.smoothScrollToPosition(adapter.getItemCount() - 1);
            }
        }, 500);
    }


    public List<SpecModel> list;

    private void getGoodsData() {
        showLoadingDialog();
        new HttpRequest<GoodsSpecResponse>()
                .with(this).setApiCode(ApiCst.getGoodsSpec)
                .addParam("goods_id", goodsId)
                .addParam("token", App.getToken(mContext))
                .setListener(new HttpRequest.OnNetworkListener<GoodsSpecResponse>() {
                    @Override
                    public void onSuccess(GoodsSpecResponse response) {
                        list = response.list;
                        if (list == null || list.size() == 0) {
                            toast("本商品不支持批量下单");
                            finish();
                            return;
                        }
                        addItemView();
                        dissmissLoadingDialog();
                    }

                    @Override
                    public void onFail(String message, GoodsSpecResponse response) {
                        dissmissLoadingDialog();
                        toast(message);
                        finish();
                    }
                }).start(new GoodsSpecResponse());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 114 && resultCode == Activity.RESULT_OK) {
            int position = data.getIntExtra("position", -1);
            if (position == -1) return;
            if (recyclerView != null) {
                recyclerView.smoothScrollToPosition(position);
                recyclerView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        recyclerView.smoothScrollToPosition(adapter.getItemCount() - 1);
                    }
                }, 500);
            }
        }
    }
}
